package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    public OrderService orderService;
    @Autowired
    public UserService userService;
    @Autowired
    public AddressBookService addressBookService;
    @Autowired
    public OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     *
     * @param page
     * @param pageSize
     * @param number 订单号
     * @param beginTime 日期判断
     * @param endTime 日期判断
     * @return
     * @throws ParseException
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime) throws ParseException {
        log.info("接收到分页数据{},{}", page, pageSize);
        //执行分页查询
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //条件过滤 1.订单号
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(number), Orders::getNumber, number);
//      String:if (beginTime!=null){System.out.println(beginTime);}
        //2. 日期
        if (beginTime != null) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse = dateFormat.parse(beginTime);
            Date parse1 = dateFormat.parse(endTime);
            lqw.between(Orders::getOrderTime, parse, parse1);
        }
        lqw.orderByDesc(Orders::getOrderTime);
        orderService.page(ordersPage, lqw);
        //拷贝分页数据
        Page<OrdersDto> dtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, dtoPage, "records");
        //获取records,注入dto,添加相关数据
        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> list = new ArrayList<>();
        records.forEach(order -> {

            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);

            //获取用户名称
            String userName = order.getConsignee();
            ordersDto.setUserName(userName);
            //获取地址
            ordersDto.setAddress(order.getAddress());
            list.add(ordersDto);
        });
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 修改订单状态
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R<Orders> status(@RequestBody Orders orders) {
        log.info("接收订单状态{}", orders);
        //将订单号id状态改为status
        Long id = orders.getId();
        Integer status = orders.getStatus();
        LambdaUpdateWrapper<Orders> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(Orders::getId, id);
        lqw.set(Orders::getStatus, status);
        orderService.update(lqw);
        return R.success(orders);
    }

    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(int page, int pageSize, HttpSession session) {
        //获取当前登录用户id
        Long currentId = BaseContext.getCurrentId();
//        Long currentId = (Long) session.getAttribute("user");
        //执行orders分页查询
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getOrderTime).eq(Orders::getUserId,currentId);
        orderService.page(pageInfo, lqw);
        //拷贝分页数据到ordersDto,忽略records
        Page<OrdersDto> dtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        //获取pageinfo将dtopage的records赋值
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> dtoList = new ArrayList<>();

        records.forEach(order -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);
            Long orderId = order.getId();
            LambdaQueryWrapper<OrderDetail> lqw2 = new LambdaQueryWrapper<>();
            //获取订单明细id
            lqw2.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> list = orderDetailService.list(lqw2);
            int size = list.size();
            ordersDto.setSumNum(size);
       /*     list.forEach(orderDetail -> {
                System.out.println(orderDetail);
            });*/
            ordersDto.setOrderDetails(list);
            dtoList.add(ordersDto);
        });
        dtoPage.setRecords(dtoList);
        return R.success(dtoPage);
    }
}
